package v1

import (
	"com.cyt.common/model"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/gvalid"
)

// 查询API对象
var Query = new(queryApi)

type queryApi struct {
	Controller
}

//查询
func (c *queryApi) Search() {
	var req *model.QueryModel
	_ = gvalid.RegisterRule("array", model.RuleArray)
	c.Valid(&req)
	for _, v := range req.Condition {
		if v.Field == "" || v.Type == "" || v.Value == "" {
			c.Result(422, "condition参数错误")
		}
		if !gstr.InArray(model.FilterType, v.Type) {
			c.Result(422, "查询不支持此类型")
		}
	}
	for _, v := range req.OrderBy {
		if v.Field == "" || v.Sort == "" || !gstr.InArray(model.SortType, v.Sort) {
			c.Result(422, "orderby参数错误")
		}
	}
	for _, v := range req.GroupBy {
		if v.Field == "" {
			c.Result(422, "groupby参数错误")
		}
	}
	query := req.Model("default", req.Table)
	columns, err := query.TableFields(req.Table)
	if err != nil {
		c.Error("查询表错误")
	}
	fields := g.SliceStr{}
	for v := range columns {
		fields = append(fields, v)
	}
	for _, v := range req.Column {
		if v == "*" {
			continue
		}
		if !gstr.InArray(fields, v) {
			c.Error("查询表字段不存在")
		}
	}
	for _, v := range req.Condition {
		if v.Type == "between" {
			val := gconv.SliceInt(v.Value)
			query = query.WhereBetween(v.Field, val[0], val[1])
		} else {
			query = query.Where(fmt.Sprintf("%s %s ?", v.Field, v.Type), req.Format(v.Value, v.Format))
		}
	}
	for _, v := range req.OrderBy {
		query = query.Order(fmt.Sprintf("%s %s", v.Field, v.Sort))
	}
	for _, v := range req.GroupBy {
		query = query.Group(v.Field)
		if v.Having != "" {
			query = query.Having(v.Having)
		}
	}
	query = query.Fields(req.Column)
	var result interface{}
	if req.Method == "FindOne" {
		result, err = query.FindOne()
	} else {
		result, err = model.Paginate(query, req.Page, req.PageSize)
	}
	if err != nil {
		c.Error("查询错误")
	}
	c.Success("成功", result)
}

